package com.gxuwz.stats.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.ResearchProjectSum;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.mapper.ResearchProjectMapper;
import com.gxuwz.stats.mapper.ResearchProjectSumMapper;
import com.gxuwz.stats.mapper.UserMapper;
import com.gxuwz.stats.service.ResearchProjectService;
import com.gxuwz.stats.service.ResearchProjectSumService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class ResearchProjectServiceImpl extends ServiceImpl<ResearchProjectMapper, ResearchProject> implements ResearchProjectService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResearchProjectMapper researchProjectMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ResearchProjectSumService researchProjectSumService;


    /**
     * 分页查询并附加用户信息
     */
//    public IPage<TotalWork> getTotalWorkListWithUserInfo(IPage<TotalWork> page, QueryWrapper<TotalWork> queryWrapper) {
//        // 调用自定义 SQL 查询方法
//        return baseMapper.selectTotalWorkWithUsername(page, queryWrapper);
//    }
    @Override
    public IPage<ResearchProject> getReProListWithUserInfo(IPage<ResearchProject> page, QueryWrapper<ResearchProject> queryWrapper) {

        // 查询分页数据
        IPage<ResearchProject> resultPage = this.page(page, queryWrapper);

        // 遍历分页结果，为每个 ResearchProject 对象附加用户信息和关联表信息
        for (ResearchProject researchProject : resultPage.getRecords()) {
            Integer userId = researchProject.getUserId();
            if (userId != null) {
                // 查询用户信息
                User user = userService.getById(userId);
                if (user != null) {
                    researchProject.setUsername(user.getUsername()); // 设置用户名
                }

                // 查询关联表信息（ResearchProjectSum）
                ResearchProjectSum projectSum = researchProjectSumService.getByUserId(userId); // 根据 userId 查询
                if (projectSum != null) {
                    researchProject.setProjectTotalScore(projectSum.getProjectTotalScore()); // 设置总分值
                    researchProject.setProjectNotes(projectSum.getProjectNotes()); // 设置备注
                } else {
                    // 如果没有对应的记录，设置默认值
                    researchProject.setProjectTotalScore(0); // 默认总分值为 0
                    researchProject.setProjectNotes(""); // 默认备注为空字符串
                }
            }
        }
//        System.out.println("resultPage="+resultPage);
        return resultPage;
    }

    @Override
    public void importResearchProjectData(MultipartFile file) throws IOException {

    }

//    public void importResearchProjectData(MultipartFile file) throws IOException {
        // 使用 EasyExcel 解析 Excel 文件
//        List<Map<Integer, String>> dataList = EasyExcel.read(file.getInputStream())
//                .sheet()
//                .doReadSync();
//
//        if (dataList.isEmpty()) {
//            throw new RuntimeException("Excel 文件为空");
//        }
//
//        // 第一行作为表头
//        Map<Integer, String> headerMap = dataList.get(0);
//
//        // 遍历数据行
//        for (int i = 1; i < dataList.size(); i++) {
//            Map<Integer, String> rowData = dataList.get(i);
//
//            // 动态解析每一行数据
//            ResearchProject nationalProject = parseProject(rowData, headerMap, "国家级");
//            ResearchProject provincialProject = parseProject(rowData, headerMap, "省部级");
//            ResearchProject municipalProject = parseProject(rowData, headerMap, "市厅级");
//            ResearchProject schoolProject = parseProject(rowData, headerMap, "校级");
//            ResearchProject horizontalProject = parseProject(rowData, headerMap, "横向");
//            ResearchProject selfFundedProject = parseProject(rowData, headerMap, "自筹");
//
//            // 获取用户信息
//            String username = rowData.get(getColumnIndex(headerMap, "姓名"));
//            if (username == null || username.trim().isEmpty()) {
//                System.err.println("Skipping invalid record due to missing username.");
//                continue;
//            }
//
//            try {
//                Integer userId = userService.getUserIdOrInsertUser(username, null, null, null, null);
//
//                // 设置用户ID并插入数据
//                if (nationalProject != null) {
//                    nationalProject.setUserId(userId);
//                    researchProjectMapper.insert(nationalProject);
//                }
//                if (provincialProject != null) {
//                    provincialProject.setUserId(userId);
//                    researchProjectMapper.insert(provincialProject);
//                }
//                if (municipalProject != null) {
//                    municipalProject.setUserId(userId);
//                    researchProjectMapper.insert(municipalProject);
//                }
//                if (schoolProject != null) {
//                    schoolProject.setUserId(userId);
//                    researchProjectMapper.insert(schoolProject);
//                }
//                if (horizontalProject != null) {
//                    horizontalProject.setUserId(userId);
//                    researchProjectMapper.insert(horizontalProject);
//                }
//                if (selfFundedProject != null) {
//                    selfFundedProject.setUserId(userId);
//                    researchProjectMapper.insert(selfFundedProject);
//                }
//            } catch (Exception e) {
//                System.err.println("Error processing user: " + username);
//                e.printStackTrace();
//            }
//        }
//    }
//
//    private ResearchProject parseProject(Map<Integer, String> rowData, Map<Integer, String> headerMap, String levelPrefix) {
//        String projectName = rowData.get(getColumnIndex(headerMap, levelPrefix + "项目名称"));
//        if (projectName == null || projectName.trim().isEmpty()) {
//            return null;
//        }
//
//        ResearchProject project = new ResearchProject();
//        project.setProjectName(projectName);
//        project.setProjectLevel(levelPrefix);
//        project.setProjectCategory(rowData.get(getColumnIndex(headerMap, levelPrefix + "类别")));
//        project.setProjectStatus(rowData.get(getColumnIndex(headerMap, levelPrefix + "项目状态")));
//        project.setProjectFunding(Double.parseDouble(rowData.getOrDefault(getColumnIndex(headerMap, levelPrefix + "经费（万）"), "0")));
//        project.setProjectScore(Integer.parseInt(rowData.getOrDefault(getColumnIndex(headerMap, levelPrefix + "分值"), "0")));
//        return project;
//    }
//
//    private int getColumnIndex(Map<Integer, String> headerMap, String columnName) {
//        for (Map.Entry<Integer, String> entry : headerMap.entrySet()) {
//            if (entry.getValue().contains(columnName)) {
//                return entry.getKey();
//            }
//        }
//        throw new RuntimeException("未找到列名：" + columnName);
//    }
}



